
package com.afd.ozblip.activity;

import java.util.HashMap;
import java.util.Map;

import com.afd.ozblip.app.CommonInfo;
import com.afd.ozblip.chat.ChatClient;
import com.afd.ozblip.entity.UserEntity;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.util.SharedUtil;
import com.afd.ozblip.util.StringUtil;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class RegisterActivity extends BaseActivity {

    /****************** 视图变量 **************************/
    private EditText userNaemEt;
    private EditText nickNameEt;
    private EditText passwordEt;
    private EditText confirmPasswordEt;
    private Button submitBtn;

    /****************** 普通变量 **************************/
    private String userNameStr;
    private String nickNameStr;
    private String passwordStr;
    private String confirmPasswordStr;
    private Map<String, Object> resultMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        // 启动返回功能
        toBack();
        // 寻找视图
        findViews();
        // 设置监听
        setListeners();
        // 获取参数
        getBundle();
    }

    /**
     * 寻找视图
     */
    public void findViews() {
        this.userNaemEt = (EditText) findViewById(R.id.et_register_userName);
        this.nickNameEt = (EditText) findViewById(R.id.et_register_nickName);
        this.passwordEt = (EditText) findViewById(R.id.et_register_password);
        this.confirmPasswordEt = (EditText) findViewById(R.id.et_register_confirmPassword);
        this.submitBtn = (Button) findViewById(R.id.btn_register_submit);
    }

    /**
     * 设置监听
     */
    public void setListeners() {
        View.OnClickListener moreClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_register_submit:
                        userNameStr = userNaemEt.getText().toString();
                        nickNameStr = nickNameEt.getText().toString();
                        passwordStr = passwordEt.getText().toString();
                        confirmPasswordStr = confirmPasswordEt.getText().toString();
                        if (verifyData()) {
                            requestRegisterInfo();
                        }
                        break;

                    default:
                        break;
                }
            }
        };
        this.submitBtn.setOnClickListener(moreClick);
    }

    /**
     * 验证数据有效性
     */
    private boolean verifyData() {
        if (StringUtil.isNullOrEmpty(userNameStr)) {
            Toast.makeText(RegisterActivity.this, "温馨提示：请输入用户名",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        if (StringUtil.isNullOrEmpty(nickNameStr)) {
            Toast.makeText(RegisterActivity.this, "温馨提示：请输入昵称!",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        if (StringUtil.isNullOrEmpty(passwordStr)) {
            Toast.makeText(RegisterActivity.this, "温馨提示：请输入密码!",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        if (passwordStr.length() < 6) {
            Toast.makeText(RegisterActivity.this, "温馨提示：密码长度不够!",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        if (StringUtil.isNullOrEmpty(confirmPasswordStr)) {
            Toast.makeText(RegisterActivity.this, "温馨提示：请输入确认密码!",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!confirmPasswordStr.equals(passwordStr)) {
            Toast.makeText(RegisterActivity.this, "温馨提示：两次密码输入不一致!",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 获取传递的参数
     */
    private void getBundle() {
        Intent intent = getIntent();
    }

    /**
     * 用户注册数据提交
     * 
     * @param paramString
     */
    public void requestRegisterInfo() {
        AsyncLoadData ald = new AsyncLoadData(this, "正在注册...",
                new AsyncAction() {
                    @Override
                    public void doLoad() throws Exception {
                        // 获取提交参数
                        Map<String, Object> registerParamMap = new HashMap<String, Object>();
                        registerParamMap.put("userName", userNameStr);
                        // passwordStr =
                        // StringUtil.getMD5Str(passwordStr);服务器已MD5加密
                        registerParamMap.put("nickName", nickNameStr);
                        registerParamMap.put("passWord", passwordStr);
                        // 发送请求
                        byte[] bUserRegiter = HttpUtil.requestByPost(
                                RegisterActivity.this,
                                Constants.USER_REGISTER_API, registerParamMap);
                        if (bUserRegiter != null) {
                            resultMap = new ParseJson()
                                    .parseRegisterRsJson(bUserRegiter);
                        }
                    }

                    @Override
                    public void loadEnd() throws Exception {
                        boolean returnFlg = (Boolean) resultMap
                                .get("returnFlg");
                        if (returnFlg) {
                            showShortToast(RegisterActivity.this, "注册成功", true);
                            final UserEntity userInfo = (UserEntity) resultMap
                                    .get("userInfo");
                            Intent indexIntent = new Intent(
                                    RegisterActivity.this, IndexActivity.class);
                            indexIntent.putExtra(
                                    IndexActivity.INTENT_TAB_CHANGE, 3);
                            isLogin = true;
                            commonUserInfo = userInfo;
                            CommonInfo.isLogin = isLogin;
                            CommonInfo.commonUserInfo = commonUserInfo;
                            // 开起chat对话连接
                            new Thread(new Runnable() {
                                public void run() {
                                    ChatClient.getInstances(userInfo
                                            .getUserId());
                                }
                            }).start();
                            startActivity(indexIntent);
                            // 存储用户信息，方便下一次登录
                            SharedUtil.storeLoginInfo(RegisterActivity.this,
                                    userNameStr, passwordStr, userInfo);
                            finish();
                        } else {
                            showShortToast(RegisterActivity.this, "注册失败", true);
                        }

                    }
                });
        ald.execute(0);
    }
}
